package data

import (
	"github.com/go-kratos/kratos/v2/log"
	"github.com/google/wire"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"user/internal/conf"
)

// ProviderSet is data providers.
var ProviderSet = wire.NewSet(NewData, NewDbEngine, NewGreeterRepo, NewUserRepo)

// Data .
type Data struct {
	// 用 Gorm 的数据库客户端，变量名保持 dbEngine
	dbEngine *gorm.DB
	// 其他数据源，比如 Redis、RabbitMQ、Kafka 等等
	// ****
}

// NewData .
func NewData(c *conf.Data, logger log.Logger, dbEngine *gorm.DB) (*Data, func(), error) {
	cleanup := func() {
		log.NewHelper(logger).Info("closing the data resources")
		sqlDB, err := dbEngine.DB()
		if err == nil {
			sqlDB.Close()
		}
	}
	return &Data{
		dbEngine: dbEngine,
	}, cleanup, nil
}

// NewDbEngine .
func NewDbEngine(c *conf.Data) (dbEngine *gorm.DB, err error) {
	dbEngine, err = gorm.Open(mysql.Open(c.Database.Source), &gorm.Config{})
	return
}
